package com.hyh.primer.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import sun.util.calendar.LocalGregorianCalendar;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 填充器
 * @author Summerday
 */

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // fieldName 指的是实体类的属性名,而不是数据库的字段名
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasSetter = metaObject.hasSetter("createTime");
        if(hasSetter){
            log.info("start insert fill ....");
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 如果自己设置了,就不需要自动填充了
        Object val = getFieldValByName("updateTime", metaObject);
        if(val == null){
            log.info("start update fill ....");
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());// 起始版本 3.3.0(推荐)
            // 或者
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
        }

    }
}
